package org.ticlib.task
{
	import org.ticlib.task.cache.ITaskCache;
	import org.ticlib.utils.Utility;

	public class InvokerBase extends Task
	{
		[Bindable] public var resultConverter:Function;
		[Bindable] public var cache:ITaskCache;
		[Bindable] public var arguments:Object;
		
		public function InvokerBase()
		{
			super();
		}
		
		public function clearCache():void {
			if(cache != null) cache.clear();
		}
		
		protected function isUseCache():Boolean{
			var args:String = Utility.serialize(this.arguments);
			if((cache != null) && (cache.isCached(args)))
			{
				var result:Object = cache.getResult(args);
				signalComplete(result);
				return true;
			}
			return false;
		}
		
		protected function signalComplete(result:Object):void
		{
			if(resultConverter != null)
				resultObject = resultConverter.apply(this, [result]);
			else
				resultObject = result;
			isComplete = true;
			
			if(cache != null)
				cache.saveCache(Utility.serialize(this.arguments), resultObject);
			dispatchEvent(new Event(Event.COMPLETE));
			
			if(chain == null) return;
			if(parent == null){
				chain.execute();
				return;
			}
			if(!parent.isComplete)
				chain.execute();
		}
		
		protected function signalCancel():void
		{
			if((chain) && (!chain.isCanceled))
				chain.stop();
			isCanceled = true;
			dispatchEvent(new Event(Event.CANCEL));
		}
	}
}